/*
 * @Author: ischen.x ischen.x@foxmail.com
 * @Date: 2024-08-22 13:13:11
 * @LastEditors: ischen.x ischen.x@foxmail.com
 * @LastEditTime: 2024-08-23 16:46:16
 * 
 * Copyright (c) 2024 by fhchengz, All Rights Reserved. 
 */
#include "MCP3021.h"

#define MCP3021_REF_VOLTAGE  (3.3)
#define MCP3021_IIC_ADDR     (0x4D<<1)

/**
 * @description: I2C write interface
 * @param data: write data
 * @param length: write length
 * @return 0: successful
 */
static mcp3021_i2c_write_fun mcp3021_i2c_write;

/**
 * @description: I2C read interface
 * @param data: read data
 * @param length: read length
 * @return 0: successful
 */
static mcp3021_i2c_read_fun mcp3021_i2c_read;

int mcp3021_set_i2c_read_write_intf(mcp3021_i2c_read_fun read, mcp3021_i2c_write_fun write)
{
    if (read && write) {
        mcp3021_i2c_read = read;
        mcp3021_i2c_write = write;
        return 0;
    } else {
        return -1;
    }
}

int mcp3021_get_voltage(double *voltage)
{
    uint8_t temp[2];
    uint16_t temp_16bit = 0;
    if (mcp3021_i2c_read(MCP3021_IIC_ADDR, temp, 2)) {
        return -1;  // I2C read error
    }
    temp_16bit = ((temp[0] << 8) | temp[1]);
    temp_16bit >>= 2;
    *voltage = (double)temp_16bit * (MCP3021_REF_VOLTAGE / 1024.0);
    return 0;
}